<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <!--
      Tips: 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮
     -->
    <form action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @clear="isResultShow=false"
      />
    </form>
    <!-- /搜索栏 -->

    <!-- 搜索结果 -->
    <search-result  v-if="isResultShow" :q="searchText" />
    <!-- /搜索结果 -->

    <!-- 联想建议 -->
    <search-suggestion @search="onSearch" :search-text="searchText" v-else-if="searchText" />
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <search-history @search="onSearch" :search-histories="searchHistories" v-else />
    <!-- /搜索历史记录 -->

  </div>
</template>

<script>
import searchHistory from './components/search-history.vue';
import SearchResult from './components/search-result.vue';
import SearchSuggestion from './components/search-suggestion.vue';
import { setItem,getItem } from '@/utils/storage'
export default {
  components: { searchHistory, SearchSuggestion, SearchResult },
  name:"Search",
  data() {
    return {
      searchText:'',  // 绑定输入框变量
      isResultShow:false,  // 搜索结果是否展示
      searchHistories:getItem('TOUTIAO_SEARCH') || []  // 搜索历史的数组
    }
  },
  watch:{
    searchHistories:{
      deep:true,
      handler(val){
        setItem('TOUTIAO_SEARCH',val)
      }
    }
  },
  methods: {
    // 键盘上面的 搜索按钮  或 enter 就会触发
    onSearch(val){
      this.searchText = val
      // 显示搜索结果
      this.isResultShow = true
      // 将输入的内容放入到搜索历史数组中去
      if(!this.searchHistories.includes(val) ){
          this.searchHistories.unshift(this.searchText)
      }
    },
    onCancel(){
      this.$router.back()
    }
  },
};
</script>
<style scoped lang="less">
.search-container {
  .van-search__action {
    color: #fff;
  }
}
</style>
